package org.cosmact.designer.vxml.gefeditor.editpart.command;

import org.cosmact.vxml.model.Dialog;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.ChangeBoundsRequest;

/**
 * Use for move dialog
 * 
 *@author YeXiaowei 234aini@gmail.com
 * 
 */
public class MoveDialogCommand extends Command {
	private EditPart part;
	private final Rectangle newBounds;
	private final Dialog dialog;
	private Rectangle oldBounds;
	private final ChangeBoundsRequest request;

	public MoveDialogCommand(final ChangeBoundsRequest request,
			final EditPart part, final Rectangle constraint) {
		this.request = request;
		this.part = part;
		this.newBounds = constraint.getCopy();
		dialog = (Dialog) part.getModel();
		setLabel("Move/Resize");
	}

	@Override
	public boolean canExecute() {
		return validRequest() && part != null
				&& (part.getModel() instanceof Dialog)
				&& newBounds != null;
	}

	@Override
	public void execute() {
		oldBounds = new Rectangle(dialog.getLocation(), dialog.getSize());
		dialog.setLocation(newBounds.getLocation());
		redo();
	}

	private boolean validRequest() {
		Object type = request.getType();
		// make sure the Request is of a type we support:
		return (RequestConstants.REQ_MOVE.equals(type)
				|| RequestConstants.REQ_MOVE_CHILDREN.equals(type)
				|| RequestConstants.REQ_RESIZE.equals(type) || RequestConstants.REQ_RESIZE_CHILDREN
				.equals(type));
	}

	@Override
	public void redo() {
		dialog.setSize(newBounds.getSize());
		dialog.setLocation(newBounds.getLocation());
	}

	@Override
	public void undo() {
		dialog.setSize(oldBounds.getSize());
		dialog.setLocation(oldBounds.getLocation());
	}
}
